package com.link.gateway.core.utils;

import com.link.gateway.core.comproperty.ReqAndRespConstants;
import org.bouncycastle.util.Strings;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 处理请求数据工具类
 *
 * @author 郭闪
 * @date   2019-08-05
 */
public class RequestDataUtils {

    public RequestDataUtils() {
    }

    /**
     * 获取ServerWebExchange存储的请求体
     * 此请求体是请求经过CacheBodyUrlAttrGatewayFilter 存储在ServerWebExchange，
     * 意味着要通过此方法获取请求体，那么filter的order的值必须大于CacheBodyUrlAttrGatewayFilter 的order的值
     * @author 郭闪
     * @date 2019/12/26
     * @param exchange
     *
     */
    public static String getReqDataStr(ServerWebExchange exchange) throws UnsupportedEncodingException {
        String cachedBody = exchange.getAttribute(ReqAndRespConstants.CACHE_REQUEST_BODY_KEY);
        if (StringUtils.isBlank(cachedBody)) {
            return  "";
        }
        return URLDecoder.decode(cachedBody, "UTF-8");
    }

    /**
     * 将请求数据转换为字符串
     * @author 郭闪
     * @date 2019/12/26
     * @param body
     *
     */
    public static String toRaw(Flux<DataBuffer> body) {
        AtomicReference<String> rawRef = new AtomicReference<>();
        body.subscribe(buffer -> {
            byte[] bytes = new byte[buffer.readableByteCount()];
            buffer.read(bytes);
            DataBufferUtils.release(buffer);
            rawRef.set(Strings.fromUTF8ByteArray(bytes));
        });
        return rawRef.get();
    }


}
